import { Form } from '@ant-design/compatible';
import {InfoCircleOutlined} from '@ant-design/icons';
import '@ant-design/compatible/assets/index.css';
import { Input, Modal, InputNumber, Upload, Button, Icon, Select, Radio, Card, Col, Tabs,message, Tooltip} from 'antd';
import { formatMessage, FormattedMessage} from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState } from 'react';
import { queryRule, updateRule, addRule, removeRule } from '../service';
import styles from '../style.less';

import CryptoJS from 'crypto-js';

// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';

// 常量
const { TextArea } = Input;
const FormItem = Form.Item;
const {TabPane} = Tabs;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  // dataModalVisible: boolean;
  isUpdate: boolean
  dataImgFormValues: any
  common: any
  imageValues: any
}

// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { form, common, isUpdate,dataImgFormValues,imageValues } = props;

  const parseDataItem = (key:any,options:any) => {
    // console.log(options);
    var obj:any = {};
    if(Array.isArray(options) && options.length>0){
      options.map(item=>{
        if(item.alias_key == key){
          obj = item;
        }
      })
    }
    return obj
  }

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [pictureVideo, setPictureVideo] = useState<any[]>([]);
  const [uploadVideoChanged, setUploadVideoChanged] = useState<boolean>(false);
  const [pictureAudio, setPictureAudio] = useState<any[]>([]);
  const [uploadAudioChanged, setUploadAudioChanged] = useState<boolean>(false);
  const [pictureFile, setPictureFile] = useState<any[]>([]);
  const [uploadFileChanged, setUploadFileChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');
  const [dataFormValues, setDataFormValues] = useState({});
  const [activeTabKey, setActivityKey] = useState<any>('1');



  const okUploadHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if(picture.length > 0){
        fieldsValue.file_id   = picture[0].file_id
        fieldsValue.file_url  = picture[0].file_url
      }
      
      console.log("submit fields ", fieldsValue)

      var submitValue = [
        {
          //请求当前一组配置参数，tag=storages
          "alias_key": 'storages',
          "item_type":'system',
          "dict_item_arr": [
            {
              "alias_key": "repair_image",
              "item_value": picture.length>0?picture[0].file_id:parseData('repair_image',imageValues),
              'item_type':"file",
            },
            {
              "alias_key": "repair_video",
              "item_value": pictureVideo.length>0?pictureVideo[0].file_id:parseData('repair_video',imageValues),
              'item_type':"file",
            },
            {
              "alias_key": "repair_audio",
              "item_value": pictureAudio.length>0?pictureAudio[0].file_id:parseData('repair_audio',imageValues),
              'item_type':"file",
            },
            {
              "alias_key": "repair_doc",
              "item_value": pictureFile.length>0?pictureFile[0].file_id:parseData('repair_doc',imageValues),
              'item_type':"file",
            }
          ]
        }
    ]
    // 如果更新成功之后，重置表单
    updateRule({config_json: JSON.stringify(submitValue)}).then((res:any) => {
      console.log('handleSubmit then success is ', JSON.stringify(submitValue))
      if(res.code == 0){
        // form.resetFields()
        message.success('保存成功');
      }
    })
    });
  };


  // 设置上传文件值
  const setUploadFile = (fileList:any) => {
    setUploadChanged(true)
    if(fileList.length>0 && fileList[0].response && fileList[0].response?.code != 0){
      message.error(fileList[0].response.message);
      return
    }
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if(fileArr.length > 0){
      setPicture(fileArr)
      // setPreviewImg(fileArr[0].file_url)
    }else if(fileArr.length === 0){
      console.log('set picture []')
      setPicture([])
    }
  }

    // 设置视频图片上传文件值
    const setVideoUploadFile = (fileList:any) => {
      setUploadVideoChanged(true)
      if(fileList.length>0 && fileList[0].response && fileList[0].response?.code != 0){
        message.error(fileList[0].response.message);
        return
      }
      let fileArr = DataHelper.getLastUploadFile(fileList)
      console.log("fileArr is ", fileArr)
      if(fileArr.length > 0){
        setPictureVideo(fileArr)
        // setPreviewImg(fileArr[0].file_url)
      }else if(fileArr.length === 0){
        console.log('set picture []')
        setPictureVideo([])
      }
    }
    // 设置视频图片上传文件值
    const setAudioUploadFile = (fileList:any) => {
      setUploadVideoChanged(true)
      if(fileList.length>0 && fileList[0].response && fileList[0].response?.code != 0){
        message.error(fileList[0].response.message);
        return
      }
      let fileArr = DataHelper.getLastUploadFile(fileList)
      console.log("fileArr is ", fileArr)
      if(fileArr.length > 0){
        setPictureAudio(fileArr)
        // setPreviewImg(fileArr[0].file_url)
      }else if(fileArr.length === 0){
        console.log('set picture []')
        setPictureAudio([])
      }
    }
    // 设置视频图片上传文件值
    const setFileUploadFile = (fileList:any) => {
      setUploadFileChanged(true)
      if(fileList.length>0 && fileList[0].response && fileList[0].response?.code != 0){
        message.error(fileList[0].response.message);
        return
      }
      let fileArr = DataHelper.getLastUploadFile(fileList)
      console.log("fileArr is ", fileArr)
      if(fileArr.length > 0){
        setPictureFile(fileArr)
        // setPreviewImg(fileArr[0].file_url)
      }else if(fileArr.length === 0){
        console.log('set picture []')
        setPictureFile([])
      }
    }

    const parseData = (key:any,options:any) => {
      // console.log(options);
      var name:any = "";
      if(Array.isArray(options) && options.length>0){
        options.map(item=>{
          if(item.alias_key == key){
            name = item?.item_value;
          }
        })
      }
      return name
    }


  // 初始化变量
  const token = BdHelper.getBdToken()

  // 编辑时初始化 picture
  const defaultPicture = DataHelper.buildFileByUrl(parseDataItem('repair_image',imageValues)?.item_file || '')
  const defaultVideoPicture = DataHelper.buildFileByUrl(parseDataItem('repair_video',imageValues)?.item_file || '')
  const defaultAudioPicture = DataHelper.buildFileByUrl(parseDataItem('repair_audio',imageValues)?.item_file || '')
  const defaultFilePicture = DataHelper.buildFileByUrl(parseDataItem('repair_doc',imageValues)?.item_file || '')

  // 是否展示图片上传按钮
  const showUploadButton = DataHelper.showUploadBtn(isUpdate, picture, defaultPicture, uploadChanged)
  const showUploadVideoButton = DataHelper.showUploadBtn(isUpdate, pictureVideo, defaultVideoPicture, uploadVideoChanged)
  const showUploadAudioButton = DataHelper.showUploadBtn(isUpdate, pictureAudio, defaultAudioPicture, uploadAudioChanged)
  const showUploadFileButton = DataHelper.showUploadBtn(isUpdate, pictureFile, defaultFilePicture, uploadFileChanged)


  const userInfo = localStorage.getItem('user-login-info');
  let fresnsClient = eval("(" + userInfo + ")");
  const timestamp = new Date().getTime().toString().substr(0,10);
  var md5String = `appId=${fresnsClient?.app_id}&platform=${fresnsClient?.platform}&timestamp=${timestamp}&key=${fresnsClient?.app_secret}`;

  // 弹出框
  // @ts-ignore
  return <div>
    <Card title={'无效状态补位'} className={styles.card} bordered={false}>
      <Col span={24}>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}  extra="当图片状态为“无效”时输出的补位提示用途图"
        label={
          <span>
            <FormattedMessage id="图片无效提示图" />
            {/* <em className={styles.optional}>
              <Tooltip title={<FormattedMessage id="当图片状态为“无效”时输出的补位提示用途图" />}>
                <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
              </Tooltip>
            </em> */}
          </span>
        }>
          {form.getFieldDecorator('picture', {
            initialValue: defaultPicture,
            // rules: [{required: true, message: '请上传图片'}],
          })(
            <Upload
              listType={'picture'}
              className={'upload-list-inline'}
              action="/api/admin/tweetfiles/upload"
              defaultFileList={defaultPicture}
              beforeUpload={(file) => {
                console.log('before upload file type:', file.type)
                // todo: 这里可以对上传文件类型做限制
                return true;
              }}
              data={{ table_type: 2 , table_key: 'repair_image' }}
              onRemove={() => setPicture([])}
              onChange={(changeObj) => setUploadFile(changeObj.fileList)}
              onPreview={() => {setPreviewImg(parseDataItem("repair_image",imageValues)?.item_file  || picture[0]?.file_url);handlePreviewModalVisible(true)}}
              headers={{
                Authorization: `Bearer ${token}`,
                'platform': fresnsClient?.platform,
                'timestamp': timestamp,
                'appId': fresnsClient?.app_id,
                'sign':  CryptoJS.MD5(md5String).toString(),
              }}
            >
              {
                showUploadButton ? (
                  <Button>
                    <Icon type="upload"/> {formatMessage({ id: 'app.base.upload' })}
                  </Button>
                ) : null
              }
            </Upload>
          )}
        </FormItem>
      </Col>
      <Col span={24}>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} extra="当视频状态为“无效”时输出的补位提示用途图"
        label={
          <span>
            <FormattedMessage id="视频无效提示图" />
            {/* <em className={styles.optional}>
              <Tooltip title={<FormattedMessage id="当视频状态为“无效”时输出的补位提示用途图" />}>
                <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
              </Tooltip>
            </em> */}
          </span>
        }>
          {form.getFieldDecorator('pictureVideo', {
            initialValue: defaultVideoPicture,
            // rules: [{required: true, message: '请上传图片'}],
          })(
            <Upload
              listType={'picture'}
              className={'upload-list-inline'}
              action="/api/admin/tweetfiles/upload"
              defaultFileList={defaultVideoPicture}
              beforeUpload={(file) => {
                console.log('before upload file type:', file.type)
                // todo: 这里可以对上传文件类型做限制
                return true;
              }}
              data={{ table_type: 2 , table_key: 'repair_video'}}
              onRemove={() => setPictureVideo([])}
              onChange={(changeObj) => setVideoUploadFile(changeObj.fileList)}
              onPreview={() => {setPreviewImg(parseDataItem("repair_video",imageValues)?.item_file || pictureVideo[0]?.file_url);handlePreviewModalVisible(true)}}
              headers={{
                Authorization: `Bearer ${token}`,
                'platform': fresnsClient?.platform,
                'timestamp': timestamp,
                'appId': fresnsClient?.app_id,
                'sign':  CryptoJS.MD5(md5String).toString(),
              }}
            >
              {
                showUploadVideoButton ? (
                  <Button>
                    <Icon type="upload"/> {formatMessage({ id: 'app.base.upload' })}
                  </Button>
                ) : null
              }
            </Upload>
          )}
        </FormItem>
      </Col>
      <Col span={24}>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} extra="当音频状态为“无效”时输出的补位提示用途图"
        label={
          <span>
            <FormattedMessage id="音频无效提示图" />
            {/* <em className={styles.optional}>
              <Tooltip title={<FormattedMessage id="当音频状态为“无效”时输出的补位提示用途图" />}>
                <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
              </Tooltip>
            </em> */}
          </span>
        }>
          {form.getFieldDecorator('pictureAudio', {
            initialValue: defaultAudioPicture,
            // rules: [{required: true, message: '请上传图片'}],
          })(
            <Upload
              listType={'picture'}
              className={'upload-list-inline'}
              action="/api/admin/tweetfiles/upload"
              defaultFileList={defaultAudioPicture}
              beforeUpload={(file) => {
                console.log('before upload file type:', file.type)
                // todo: 这里可以对上传文件类型做限制
                return true;
              }}
              data={{ table_type: 2 , table_key: 'repair_audio'}}
              onRemove={() => setPictureAudio([])}
              onChange={(changeObj) => setAudioUploadFile(changeObj.fileList)}
              onPreview={() => {setPreviewImg(parseDataItem("repair_audio",imageValues)?.item_file || pictureAudio[0]?.file_url); handlePreviewModalVisible(true)}}
              headers={{
                Authorization: `Bearer ${token}`,
                'platform': fresnsClient?.platform,
                'timestamp': timestamp,
                'appId': fresnsClient?.app_id,
                'sign':  CryptoJS.MD5(md5String).toString(),
              }}
            >
              {
                showUploadAudioButton ? (
                  <Button>
                    <Icon type="upload"/> {formatMessage({ id: 'app.base.upload' })}
                  </Button>
                ) : null
              }
            </Upload>
          )}
        </FormItem>
      </Col>
      <Col span={24}>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} extra="当文档状态为“无效”时输出的补位提示用途图"
        label={
          <span>
            <FormattedMessage id="文档无效提示图" />
            {/* <em className={styles.optional}>
              <Tooltip title={<FormattedMessage id="当文档状态为“无效”时输出的补位提示用途图" />}>
                <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
              </Tooltip>
            </em> */}
          </span>
        }>
          {form.getFieldDecorator('pictureFile', {
            initialValue: defaultFilePicture,
            // rules: [{required: true, message: '请上传图片'}],
          })(
            <Upload
              listType={'picture'}
              className={'upload-list-inline'}
              action="/api/admin/tweetfiles/upload"
              defaultFileList={defaultFilePicture}
              beforeUpload={(file) => {
                console.log('before upload file type:', file.type)
                // todo: 这里可以对上传文件类型做限制
                return true;
              }}
              data={{ table_type: 2 , table_key: 'repair_doc'}}
              onRemove={() => setPictureFile([])}
              onChange={(changeObj) => setFileUploadFile(changeObj.fileList)}
              onPreview={() => {setPreviewImg(parseDataItem("repair_doc",imageValues)?.item_file || pictureFile[0]?.file_url); handlePreviewModalVisible(true)}}
              headers={{
                Authorization: `Bearer ${token}`,
                'platform': fresnsClient?.platform,
                'timestamp': timestamp,
                'appId': fresnsClient?.app_id,
                'sign':  CryptoJS.MD5(md5String).toString(),
              }}
            >
              {
                showUploadFileButton ? (
                  <Button>
                    <Icon type="upload"/> {formatMessage({ id: 'app.base.upload' })}
                  </Button>
                ) : null
              }
            </Upload>
          )}
        </FormItem>
      </Col>
    </Card>
      <Col span={15}>
        <div style={{display: 'flex',justifyContent:'center',marginTop:20,}}>
          <Button type="primary" style={{marginLeft:30}} onClick={()=>{okUploadHandle()}}>保存</Button>
        </div>
      </Col>
    {
      previewModelVisible && (
        <PreviewForm
          previewModelVisible={previewModelVisible}
          onVisibleModel={handlePreviewModalVisible}
          previewImg={previewImg}
        />
      )
    }
  </div>;
};

export default Form.create<DataFormProps>()(DataForm);
